package com.shiftychess.piece
{
	import com.shiftychess.board.Colour;
	import com.shiftychess.board.Position;
	import com.shiftychess.model.GameModel;
	
	[Bindable]
	[RemoteClass(alias="com.shiftychess.model.piece.Pawn")]
	public class Pawn implements IChessPiece {
		public var pieceId:int;
		public var type:String;
		public var colour:String;
		public var positionX:String;
		public var positionY:int;
		
		public function Pawn() {
		}
		
		public function get position():Position {
			var pos:Position = new Position();
			pos.x = positionX;
			pos.y = positionY;
			
			return pos;
		}
						
		public function canMove(position:Position):Boolean {
			
			var currentX:int = Position.convertXtoInt(positionX);
			var requestX:int = Position.convertXtoInt(position.x);
			
			//move one ahead on empty space
			//or move two ahead on empty if not moved yet
			if(requestX == currentX) {
				var posInBetween:Position;
				if(colour == Colour.WHITE) {
					if(position.y == positionY + 1) {
						return GameModel.checkEmptySpace(position);
					} else if(positionY == 2 && position.y == positionY + 2) {
						posInBetween = new Position();
						posInBetween.x = position.x;
						posInBetween.y = position.y + 1;
						return GameModel.checkEmptySpace(position) && GameModel.checkEmptySpace(posInBetween);
					}  else {
						return false;
					}
				} else {
					if(position.y == positionY - 1) {
						return GameModel.checkEmptySpace(position);
					} else if(positionY == 7 && position.y == positionY - 2) {
						posInBetween = new Position();
						posInBetween.x = position.x;
						posInBetween.y = position.y - 1;
						return GameModel.checkEmptySpace(position) && GameModel.checkEmptySpace(posInBetween);
					}  else {
						return false;
					}					
				}
			//move one ahead-left or ahead-right if space occupied by other colour
			} else if(requestX == currentX + 1 || requestX == currentX - 1) {
				if(colour == Colour.WHITE) {
					if(position.y == positionY + 1) {
						return GameModel.checkEnemySpace(position, this.colour);
					}  else {
						return false;
					}
				} else {
					if(position.y == positionY - 1) {
						return GameModel.checkEnemySpace(position, this.colour);
					}  else {
						return false;
					}					
				}
			}
			
			return false;
		}
		
		public function move(position:Position):void {
			//update position
			positionX = position.x;
			positionY = position.y;
			
			//update board
			GameModel.movePiece(pieceId, position);
			
			//check or checkmate?
			GameModel.isCheckMate();
		}
	}
}